/*
 * Copyright (c) 2013, Klaus Hauschild
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided
 * that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice, this list of conditions and
 *     the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
 *     and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package de.hauschild.utilsn.core.keyboard;

import java.util.HashSet;
import java.util.Set;

import playn.core.Key;
import playn.core.Keyboard.Event;
import playn.core.Keyboard.Listener;
import playn.core.Keyboard.TypedEvent;
import playn.core.PlayN;

/**
 * @since 0.1.0
 * 
 * @author Klaus Hauschild
 */
public class Keys {

  private static boolean INITIALIZED;
  private static final Set<Key> KEYS_DOWN = new HashSet<Key>();
  private static final Set<Listener> LISTENERS = new HashSet<Listener>();

  public static void init() {
    if (INITIALIZED) {
      return;
    }
    PlayN.keyboard().setListener(new Listener() {

      @Override
      public void onKeyDown(final Event event) {
        KEYS_DOWN.add(event.key());
        for (final Listener listener : LISTENERS) {
          listener.onKeyDown(event);
        }
      }

      @Override
      public void onKeyTyped(final TypedEvent event) {
        for (final Listener listener : LISTENERS) {
          listener.onKeyTyped(event);
        }
      }

      @Override
      public void onKeyUp(final Event event) {
        KEYS_DOWN.remove(event.key());
        for (final Listener listener : LISTENERS) {
          listener.onKeyUp(event);
        }
      }

    });
    INITIALIZED = true;
  }

  public static Set<Key> keysDown() {
    return KEYS_DOWN;
  }

  public void addListener(final Listener listener) {
    LISTENERS.add(listener);
  }

  public void removeListener(final Listener listener) {
    LISTENERS.remove(listener);
  }

}
